package com.falm.maker.generator;

import com.falm.maker.entity.DataModel;
import com.falm.maker.entity.enums.GenerateTypeEnum;
import com.falm.maker.factory.GenerateFactory;
import com.falm.maker.generator.file.FileGenerate;
import com.falm.maker.generator.file.GenerateExecutor;
import com.falm.maker.meta.Meta;
import com.falm.maker.meta.MetaManager;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * @author Administrator
 */
public class MainGenerator {
    public static final Logger logger = LoggerFactory.getLogger(MainGenerator.class);

    public static void doGenerate(DataModel config) {
        Meta metaObject = MetaManager.getMetaObject();

        Meta.FileConfigDTO fileConfig = metaObject.getFileConfig();
        String inputRootPath = fileConfig.getInputRootPath();
        String outputRootPath = fileConfig.getOutputRootPath();
        fileConfig.getFiles().forEach(fileInfo -> {
            String generateType = fileInfo.getGenerateType();
            String beanType = fileInfo.getBeanType();
            try {
                Object dataModel = getDataModel(beanType);
                GenerateTypeEnum generateTypeEnum = GenerateTypeEnum.codeOf(generateType);
                if (ObjectUtils.isNotEmpty(generateTypeEnum)) {
                    FileGenerate fileGenerate = GenerateFactory.createExecutor(generateTypeEnum);
                    GenerateExecutor generateExecutor = new GenerateExecutor(fileGenerate);
                    fileGenerate.setDataModel(dataModel);
                    generateExecutor.doGenerate(concatPath(inputRootPath, fileInfo.getInputPath()),
                            concatPath(outputRootPath, fileInfo.getOutputPath()));
                }
            } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException |
                     IllegalAccessException | InstantiationException | IOException e) {
                throw new RuntimeException(e);
            }

        });
    }

    /**
     * 拼接绝对路径
     * @param rootPath 项目根路径
     * @param path 项目相对路径
     * @return 文件具体路径
     */
    private static String concatPath(String rootPath, String path) {
        String property = System.getProperty("user.dir");
        return StringUtils.join(property, rootPath, path);
    }

    private static Object getDataModel(String beanType)
            throws ClassNotFoundException, NoSuchMethodException,
            InvocationTargetException, InstantiationException,
            IllegalAccessException {
        if (!StringUtils.isEmpty(beanType)) {
            Class<?> aClass = Class.forName(beanType);
            return aClass.getDeclaredConstructor().newInstance();
        }
        return null;
    }
}
